package com.summer.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.summer.content.dao.CourseTeacherMapper;
import com.summer.commonException.XueChengException;
import com.summer.content.service.CourseTeacherService;
import com.summer.pojo.CourseTeacher;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CourseTeacherServiceImpl implements CourseTeacherService {

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;

    @Override
    public List<CourseTeacher> getListByCourseId(Long courseId) {
        // 调用mapper查询
        LambdaQueryWrapper<CourseTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CourseTeacher::getCourseId, courseId);
        // 封装返回结果
        return courseTeacherMapper.selectList(lqw);
    }

    @Override
    public CourseTeacher saveTeacher(CourseTeacher courseTeacher) {
        // 若id 存在则修改，否则添加
        Long id = courseTeacher.getId();
        // 新增
        if (id == null){
            CourseTeacher courseTeacherNew = new CourseTeacher();
            BeanUtils.copyProperties(courseTeacher, courseTeacherNew);
            courseTeacherNew.setCreateDate(LocalDateTime.now());
            // 调用mapper
            int insert = courseTeacherMapper.insert(courseTeacherNew);
            if(insert <= 0){
                XueChengException.cast("添加教师失败");
            }
            // 封装数据返回
            return courseTeacherNew;
        }
        // 修改
        // 数据准备
        CourseTeacher courseTeacherSelect = courseTeacherMapper.selectById(id);
        if (StringUtils.isEmpty(courseTeacherSelect)){
            XueChengException.cast("修改失败");
        }
        // 封装数据
        BeanUtils.copyProperties(courseTeacher, courseTeacherSelect);

        // 调用mapper修改
        int i = courseTeacherMapper.updateById(courseTeacherSelect);
        if (i <= 0){
            XueChengException.cast("修改失败");
        }
        // 返回数据
        return courseTeacherSelect;
    }

    @Override
    public void deleteTeacher(Long courseId, Long id) {
        // 数据准备
        // 调用mapper delete course_teacher where course_id = ? and id = ?
        LambdaQueryWrapper<CourseTeacher> lqw = new LambdaQueryWrapper<>();
        lqw.eq(CourseTeacher::getId, id).eq(CourseTeacher::getCourseId, courseId);
        int delete = courseTeacherMapper.delete(lqw);
        if (delete <= 0){
            XueChengException.cast("删除失败");
        }
    }
}
